#include "../include/server.h"
void *thread_func(void *args)
{
    int ret;
    printf("thread_func pid=%ld\n", pthread_self());
    Thread_Pool *thread_pool = (Thread_Pool *)args;
    while (1)
    {
        ret = pthread_mutex_lock(&thread_pool->tqueue.mutex);
        PTHREAD_ERROR_CHECK(ret, "pthread_mutex_lock");
        while (thread_pool->tqueue.qsize == 0)
        {
            ret = pthread_cond_wait(&thread_pool->tqueue.cond, &thread_pool->tqueue.mutex);
            PTHREAD_ERROR_CHECK(ret, "pthread_cond_wait");
            if (thread_pool->exit_flag == 1)
            {
                pthread_mutex_unlock(&thread_pool->tqueue.mutex);
                pthread_exit(NULL);
            }
        }
        Task task;
        memcpy(&task, thread_pool->tqueue.front, sizeof(Task));
        pop_queue(&thread_pool->tqueue);
        ret = pthread_mutex_unlock(&thread_pool->tqueue.mutex);
        PTHREAD_ERROR_CHECK(ret, "pthread_muetx_unlock");
        ret = deal_cmd(&task);
        if (ret == -1)
        {
            close(task.usr.sfd);
            printf("pthread %ld is free\n", pthread_self());
        }
        if (thread_pool->exit_flag == 1)
        {
            pthread_exit(NULL);
        }
    }
}
void add_epoll(int efd, int sfd)
{
    struct epoll_event event;
    event.data.fd = sfd;
    event.events = EPOLLIN;
    int ret = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event);
    ERROR_CHECK(ret, -1, "epoll_ctl");
}
void add_queue(Task_Queue *task_queue, Login_Usr *login_usr, MYSQL *mysql_con)
{
    Task *task = malloc(sizeof(Task));
    memcpy(&task->usr, login_usr, sizeof(task->usr));
    printf("add_queue usr.sfd=%d\n", task->usr.sfd);
    task->next = NULL;
    task->mysql_con = mysql_con;
    if (task_queue->qsize == 0)
    {
        task_queue->front = task;
        task_queue->tail = task;
    }
    else
    {
        task_queue->tail->next = task;
        task_queue->tail = task;
    }
    task_queue->qsize++;
}
void pop_queue(Task_Queue *task_queue)
{
    Task *task = task_queue->front;
    if (task_queue->qsize == 1)
    {
        task_queue->front = NULL;
        task_queue->tail = NULL;
    }
    else
    {
        task_queue->front = task_queue->front->next;
    }
    task_queue->qsize--;
    free(task);
}